package com.lihan.services.impl;

import cn.hutool.core.bean.BeanUtil;
import com.lihan.enums.MsgSignFlagEnum;
import com.lihan.mapper.ChatMsgMapper;
import com.lihan.mapper.UserMapperCustom;
import com.lihan.model.vo.MessageVo;
import com.lihan.netty.ChatMsg;
import com.lihan.services.IChatService;
import org.n3r.idworker.Sid;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: IChatServiceImpl
 * Package: com.lihan.services.impl
 * Description:
 *
 * @Author 李涵
 * @Create 2025-05-08 21:57
 * @Version 1.0
 */
@Service
public class IChatServiceImpl implements IChatService {

    @Resource
    Sid sid;

    @Resource
    private UserMapperCustom userMapperCustom;

    @Resource
    private ChatMsgMapper chatMsgMapper;

    /*
     * 保存消息到数据库中
     * */
    @Override
    public String savaMsg(ChatMsg chatMsg) {
        //封装消息的pojo对象
        com.lihan.model.entity.ChatMsg msgDB = new com.lihan.model.entity.ChatMsg();
        String msgId = sid.nextShort();

        msgDB.setId(msgId);
        msgDB.setAcceptUserId(chatMsg.getReceiveId());
        msgDB.setSendUserId(chatMsg.getSendId());
        msgDB.setCreateTime(new Date());
        msgDB.setSignFlag(MsgSignFlagEnum.unsign.type); //消息的状态未签收
        msgDB.setMsg(chatMsg.getMsg());

        chatMsgMapper.insert(msgDB);
        return msgId;
    }
    /*
     * 批量更改消息的签收标志
     * */
    @Override
    public void updateMsgSigned(List<String> msgIdList) {
        userMapperCustom.batchUpdateMsgSigned(msgIdList);
    }

    @Override
    public List<com.lihan.model.entity.ChatMsg> getUnReadMsgList(String acceptId) {
        List<com.lihan.model.entity.ChatMsg> result = chatMsgMapper.getUnReadMsgListByAcceptId(acceptId);
        return result;
    }

    @Override
    public List<MessageVo> getHistoryMsgList(String acceptId) {
        List<com.lihan.model.entity.ChatMsg> result = chatMsgMapper.getHistoryMsgListByAcceptId(acceptId);

        List<MessageVo> messageVos = result.stream().map(item -> {
            MessageVo messageVo = BeanUtil.copyProperties(item, MessageVo.class);
            if (acceptId.equals(item.getSendUserId())) {
                messageVo.setFlag(1);
            }else {
                messageVo.setFlag(2);
            }
            return messageVo;
        }).collect(Collectors.toList());

        return messageVos;
    }
}
